using System;
using System.Collections.Generic;
using System.Linq;

namespace Dorm.Maps
{
    public class MapLocator
    {
        private static List<IEntityMap> entityMaps;

        private static void LoadAllMaps()
        {
            Type[] mapTypes = GetAllEntityMapTypes();

            entityMaps = new List<IEntityMap>();

            foreach (var mapType in mapTypes)
                entityMaps.Add((IEntityMap)Activator.CreateInstance(mapType));
        }

        public static Type[] GetAllEntityMapTypes()
        {
            var assemblyName = System.Configuration.ConfigurationManager.AppSettings["MapsAssemblyName"].ToString();
            var assemblyWithMaps = System.Reflection.Assembly.LoadWithPartialName(assemblyName);
            return assemblyWithMaps.GetTypes()
                .Where(t => t.BaseType != null
                         && (t.BaseType.Name.StartsWith("EntityMap")
                          || t.BaseType.Name.StartsWith("ComponentMap"))).ToArray();
        }

        public static List<MappedProperty> GetMap<T>()
        {
            return GetMap(typeof(T));
        }

        public static List<MappedProperty> GetMap(Type type)
        {
            if (entityMaps == null)
                LoadAllMaps();

            var map = entityMaps.Where(e => e.GetType().BaseType.GetGenericArguments()[0].Name == type.Name).FirstOrDefault();

            if (map == null)
                throw new ApplicationException("Map configuration not found for the " + type.Name + " type.");

            return map.MappedProperties;            
        }
    }
}
